# -*- coding: utf-8 -*-
# @description: 
# @File  : verify_code.py
# @Time  :2022-08-10 17:08:23
# @Author:selfeasy
# @Email :selfeasy@qq.com

from io import BytesIO
from PIL import Image, ImageFont, ImageDraw, ImageFilter
import random,string

class imageCode(object):
    '''
    验证码处理
    '''
    def rndColor(self):
        return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

    def geneText(self):
        return ''.join(random.sample(string.ascii_letters + string.digits, 4))

    def drawLine(self,draw, num, width, height):
        '''划线
        '''
        for num in range(num):
            x1 = random.randint(0, width / 2)
            y1 = random.randint(0, height / 2)
            x2 = random.randint(0, width)
            y2 = random.randint(height / 2, height)
            draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
    
    def getVerifyCode(self):
        '''生成验证码图形'''
        code = self.geneText()
        width, height = 120, 50
        im = Image.new('RGB', (width, height), 'white') #构建图像
        font = ImageFont.truetype('./Arial.ttf', 40)#字体
        draw = ImageDraw.Draw(im) #画图
        # 绘制字符串
        for item in range(4):
            draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
            text=code[item], fill=self.rndColor(), font=font)
        self.drawLine(draw, 2, width, height)
        return im, code
    
    def getImageCode(self):
        image, code = self.getVerifyCode()
        # 图片以二进制形式写入
        buf = BytesIO()
        image.save(buf, 'jpeg')
        buf_str = buf.getvalue()
        print(image)
        print(code)
        print(buf_str)

code=imageCode()
code.getImageCode()